package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;


@Service
public class VoiceService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private VoiceApi voiceApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;



    /**
     * 桃花传音-发送语音
     */
    public ResponseEntity<Object> sendVoice(MultipartFile soundFile) throws Exception {

//        视频上传至fastdfs
        String voiceFilename = soundFile.getOriginalFilename();

        String ext = voiceFilename.substring(voiceFilename.lastIndexOf(".") + 1);
//        参数1、文件输入流 2、文件大小 3、后缀
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), ext, null);

        String voiceUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

//        保存voice
        Voice voice = new Voice();

        voice.setUserId(UserHolder.getUserId());
        voice.setVoiceUrl(voiceUrl);
        voice.setCreated(System.currentTimeMillis());

//        Random random = new Random();
//        Long i = Long.valueOf(random.nextLong());
//        voice.setVid(i);

        voiceApi.save(voice);

        return ResponseEntity.ok(null);

    }

    /**
     * 桃花传音-接收语音
     */
    public ResponseEntity<Object> receiving() {
//
////        获取当前用户id(持久层根据当前用户id，查询除自己外的语音)
//        Long userId = UserHolder.getUserId();
//
////        随机获取一条语音voice
//        Voice voice = voiceApi.findVid(userId);
//
////        根据当前用户id，查询当前用户剩余接收语音次数
//        Integer remainingTimes = voice.getRemainingTimes();
//
//        voiceApi.update(userId,remainingTimes);
////        根据当前用户id查询语音信息
//        Voice voice1 = voiceApi.findByUserId(userId);
//        Integer r1 = voice1.getRemainingTimes();
//
////        创建vo封装数据
//        VoiceVo vo = new VoiceVo();
//        BeanUtils.copyProperties(voice, vo);
//
//        UserInfo userInfo = userInfoApi.findById(voice.getUserId());
//        if (userInfo != null) {
//            BeanUtils.copyProperties(userInfo, vo);
//            vo.setId(userInfo.getId());
//        }
//
//        vo.setRemainingTimes(r1);
//////        删除获取到的语音[为方便测试，先行注销]
////        ObjectId id = voice.getId();
////        voiceApi.delete(id);
//
//        return ResponseEntity.ok(vo);


//        获取当前登录用户
        Long userId = UserHolder.getUserId();
//        随机获取一条语音voice
        Voice vi = voiceApi.findVid(userId);
        Long id = vi.getUserId();// 语音作者id


        UserInfo userInfo = userInfoApi.findById(id);
//        封装数据
        VoiceVo vo = new VoiceVo();
        BeanUtils.copyProperties(vi,vo);


        if (userInfo!=null){
            BeanUtils.copyProperties(userInfo,vo);
        }
//        获取当前用户剩余次数
        UserInfo info = userInfoApi.findById(userId);
        Integer remainingTimes = info.getRemainingTimes();

        if (remainingTimes>=0) {
//        根据用户id,修改次数
            info.setRemainingTimes(remainingTimes - 1);
            userInfoApi.update(info);

            UserInfo info1 = userInfoApi.findById(userId);

            vo.setRemainingTimes(info1.getRemainingTimes());
        }

//        删除获取到的语音[为方便测试，先行注销]
        ObjectId id1 = vi.getId();
        voiceApi.delete(id1);

        return ResponseEntity.ok(vo);
    }


//    定时类，定时更新接收语音次数
    public  void updateremainingTimes(){
        Long userId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        userInfo.setRemainingTimes(10);
//        定时类，定时更新接收次数
//        voiceApi.updateremainingTimes(userId);
        userInfoApi.update(userInfo);
    }

    /**
     * 是否喜欢（新增接口）
     * uid这里是随机获取到语音作者id
     */
    public ResponseEntity<Object> alreadyLove(Long uid) {
//        获取当前用户id
        Long userId = UserHolder.getUserId();
////        查询当前用户朋友列表里有没有这个语音作者的id
//        friendApi.findByUid(userId,uid);

//        删除粉丝中的喜欢数据
        userLikeApi.delete(userId,uid);

//        记录双向的好友关系
        friendApi.save(userId,uid);
//        注册好友关系到环信
        huanXinTemplate.contactUsers(userId,uid);

        return ResponseEntity.ok(null);
    }

//    /**
//     * 桃花传音-喜欢
//     * 接口路径：GET/tanhua/:id/love
//     * id为语音id
//     */
//    public ResponseEntity<Object> love(Long id) {
////        获取当前用户id
//        Long userId = UserHolder.getUserId();
//
////        根据语音id，查找语音信息
//        Voice voice = voiceApi.findById(id);
//
//        String key = "public_love_"+userId+"_"+id;
//        redisTemplate.opsForValue().set(key,1);
//
//
//        return ResponseEntity.ok(null);
//    }
}
